<template>
  <div class="create-or-edit">
    <el-form label-position="right" size="small" label-width="150px">
      <el-form-item label="角色名称：">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="角色编码：" >
        <el-input v-model="form.code"></el-input>
      </el-form-item>
      <el-form-item label="描述：">
        <el-input type="textarea" :rows="4" style="width: 250px" v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { createOrUpdate, getRoleById } from '@/services/role'

export default ({
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: [Number, String]
    }
  },
  name: 'CreateOrEdit',
  data () {
    return {
      form: {
        name: '',
        code: '',
        description: ''
      }
    }
  },
  created () {
    if (this.isEdit) {
      this.loadRole()
    }
  },
  methods: {
    onCancel () {
      // 设置取消状态，让父组件处理
      this.$emit('cancel')
      this.form = {}
    },
    // 根据角色 id 获取当前角色信息
    async loadRole () {
      const { data } = await getRoleById(this.roleId)
      if (data.code === '000000') {
        this.form = data.data
      }
    },
    async onSubmit () {
      const { data } = await createOrUpdate(this.form)
      if (data.code === '000000') {
        // 关闭提示框(需要子组件向父组件传递状态)
        this.$emit('success')
        // 设置成功提示
        if (this.isEdit) {
          this.$message('编辑成功')
        } else {
          this.$message('添加成功')
        }
        // 清除表单内容
        this.form = {}
      }
    }
  }
})
</script>

<style lang="scss" scoped>
  .create-or-edit {
    .el-input {
      width: 250px;
    }
    .el-button {
      float: right;
      margin-left: 15px;
    }
  }
</style>
